const express = require('express');
const router = express.Router();
const { exec } = require('child_process');
const { db } = require('../app');

// 获取节点列表（仅管理员）
router.get('/', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    db.all('SELECT * FROM nodes ORDER BY created_at DESC', (err, nodes) => {
        if (err) {
            return res.status(500).json({ error: '获取节点列表失败' });
        }
        res.json({ success: true, nodes });
    });
});

// 创建新节点（仅管理员）
router.post('/create', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const { name, host, port, username, password, private_key } = req.body;

    if (!name || !host || !username) {
        return res.status(400).json({ error: '名称、主机和用户名是必需的' });
    }

    // 验证连接
    const sshCommand = password 
        ? `sshpass -p "${password}" ssh -o StrictHostKeyChecking=no -p ${port || 22} ${username}@${host} "echo 'Connection successful'"`
        : `ssh -i "${private_key}" -o StrictHostKeyChecking=no -p ${port || 22} ${username}@${host} "echo 'Connection successful'"`;

    exec(sshCommand, (error, stdout, stderr) => {
        if (error) {
            return res.status(400).json({ error: '无法连接到节点，请检查连接信息' });
        }

        // 插入数据库
        db.run(
            'INSERT INTO nodes (name, host, port, username, password, private_key, status) VALUES (?, ?, ?, ?, ?, ?, ?)',
            [name, host, port || 22, username, password, private_key, 'online'],
            function(err) {
                if (err) {
                    return res.status(500).json({ error: '创建节点失败' });
                }
                res.json({ 
                    success: true, 
                    message: '节点创建成功', 
                    node: { 
                        id: this.lastID, 
                        name, 
                        host, 
                        status: 'online' 
                    } 
                });
            }
        );
    });
});

// 更新节点（仅管理员）
router.put('/:id', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const nodeId = req.params.id;
    const { name, host, port, username, password, private_key } = req.body;

    if (!name || !host || !username) {
        return res.status(400).json({ error: '名称、主机和用户名是必需的' });
    }

    // 验证连接
    const sshCommand = password 
        ? `sshpass -p "${password}" ssh -o StrictHostKeyChecking=no -p ${port || 22} ${username}@${host} "echo 'Connection successful'"`
        : `ssh -i "${private_key}" -o StrictHostKeyChecking=no -p ${port || 22} ${username}@${host} "echo 'Connection successful'"`;

    exec(sshCommand, (error, stdout, stderr) => {
        if (error) {
            return res.status(400).json({ error: '无法连接到节点，请检查连接信息' });
        }

        // 更新数据库
        db.run(
            'UPDATE nodes SET name = ?, host = ?, port = ?, username = ?, password = ?, private_key = ?, status = ? WHERE id = ?',
            [name, host, port || 22, username, password, private_key, 'online', nodeId],
            (err) => {
                if (err) {
                    return res.status(500).json({ error: '更新节点失败' });
                }
                res.json({ success: true, message: '节点更新成功' });
            }
        );
    });
});

// 删除节点（仅管理员）
router.delete('/:id', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const nodeId = req.params.id;

    // 检查节点上是否有服务器
    db.get('SELECT COUNT(*) as count FROM servers WHERE node_id = ?', [nodeId], (err, result) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        if (result.count > 0) {
            return res.status(400).json({ error: '该节点上还有服务器，无法删除' });
        }

        // 删除节点
        db.run('DELETE FROM nodes WHERE id = ?', [nodeId], (err) => {
            if (err) {
                return res.status(500).json({ error: '删除节点失败' });
            }
            res.json({ success: true, message: '节点删除成功' });
        });
    });
});

// 获取节点状态
router.get('/:id/status', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const nodeId = req.params.id;

    db.get('SELECT * FROM nodes WHERE id = ?', [nodeId], (err, node) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        if (!node) {
            return res.status(404).json({ error: '节点不存在' });
        }

        // 检查节点连接状态
        const sshCommand = node.password 
            ? `sshpass -p "${node.password}" ssh -o StrictHostKeyChecking=no -p ${node.port} ${node.username}@${node.host} "echo 'Connection successful'"`
            : `ssh -i "${node.private_key}" -o StrictHostKeyChecking=no -p ${node.port} ${node.username}@${node.host} "echo 'Connection successful'"`;

        exec(sshCommand, (error, stdout, stderr) => {
            const status = error ? 'offline' : 'online';
            
            // 更新节点状态
            db.run('UPDATE nodes SET status = ? WHERE id = ?', [status, nodeId]);

            // 获取节点系统信息
            const infoCommand = node.password 
                ? `sshpass -p "${node.password}" ssh -o StrictHostKeyChecking=no -p ${node.port} ${node.username}@${node.host} "uname -a && free -h && df -h"`
                : `ssh -i "${node.private_key}" -o StrictHostKeyChecking=no -p ${node.port} ${node.username}@${node.host} "uname -a && free -h && df -h"`;

            exec(infoCommand, (infoError, infoStdout, infoStderr) => {
                const systemInfo = infoError ? '无法获取系统信息' : infoStdout;

                res.json({ 
                    success: true, 
                    status: status,
                    system_info: systemInfo,
                    node: {
                        id: node.id,
                        name: node.name,
                        host: node.host,
                        created_at: node.created_at
                    }
                });
            });
        });
    });
});

// 生成节点安装指令
router.get('/:id/install-command', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const nodeId = req.params.id;

    db.get('SELECT * FROM nodes WHERE id = ?', [nodeId], (err, node) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        if (!node) {
            return res.status(404).json({ error: '节点不存在' });
        }

        // 获取面板公网IP
        db.get("SELECT value FROM settings WHERE key = 'panel_ip'", (err, setting) => {
            const panelIp = setting ? setting.value : 'localhost';

            // 生成安装脚本
            const installScript = `#!/bin/bash
# Minecraft面板节点安装脚本
# 节点名称: ${node.name}
# 面板地址: ${panelIp}

# 设置国内镜像源
echo "配置国内镜像源..."
sudo apt-get update
sudo apt-get install -y apt-transport-https ca-certificates curl software-properties-common

# 安装Docker（使用国内镜像）
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

# 配置Docker国内镜像
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://registry.docker-cn.com", "https://docker.mirrors.ustc.edu.cn"]
}
EOF

# 重启Docker服务
sudo systemctl daemon-reload
sudo systemctl restart docker

# 安装必要工具
sudo apt-get install -y sshpass wget unzip

# 创建Minecraft服务器目录
sudo mkdir -p /opt/minecraft-servers
sudo chown -R $USER:$USER /opt/minecraft-servers

# 下载Minecraft服务器被控程序
wget -O /tmp/node-agent.zip "http://${panelIp}:3000/api/node-agent/download"
unzip -o /tmp/node-agent.zip -d /opt/minecraft-panel-node
rm /tmp/node-agent.zip

# 设置权限
chmod +x /opt/minecraft-panel-node/node-agent

# 创建systemd服务
sudo tee /etc/systemd/system/minecraft-node-agent.service <<-'EOF'
[Unit]
Description=Minecraft Panel Node Agent
After=network.target

[Service]
Type=simple
User=$USER
WorkingDirectory=/opt/minecraft-panel-node
ExecStart=/opt/minecraft-panel-node/node-agent
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# 启动服务
sudo systemctl daemon-reload
sudo systemctl enable minecraft-node-agent
sudo systemctl start minecraft-node-agent

echo "节点安装完成！"
echo "节点名称: ${node.name}"
echo "节点地址: ${node.host}"
echo "面板地址: ${panelIp}:3000"
`;

            res.json({ 
                success: true, 
                install_command: `curl -sSL "http://${panelIp}:3000/api/node/install/${nodeId}" | bash`,
                install_script: installScript
            });
        });
    });
});

// 测试节点连接
router.post('/:id/test', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const nodeId = req.params.id;

    db.get('SELECT * FROM nodes WHERE id = ?', [nodeId], (err, node) => {
        if (err) {
            return res.status(500).json({ error: '数据库错误' });
        }
        if (!node) {
            return res.status(404).json({ error: '节点不存在' });
        }

        // 测试连接
        const sshCommand = node.password 
            ? `sshpass -p "${node.password}" ssh -o StrictHostKeyChecking=no -p ${node.port} ${node.username}@${node.host} "echo 'Connection successful' && docker --version"`
            : `ssh -i "${node.private_key}" -o StrictHostKeyChecking=no -p ${node.port} ${node.username}@${node.host} "echo 'Connection successful' && docker --version"`;

        exec(sshCommand, (error, stdout, stderr) => {
            if (error) {
                return res.json({ 
                    success: false, 
                    message: '连接失败',
                    error: stderr 
                });
            }

            res.json({ 
                success: true, 
                message: '连接成功',
                output: stdout 
            });
        });
    });
});

// 获取节点上的服务器列表
router.get('/:id/servers', (req, res) => {
    if (!req.session.user || req.session.user.role !== 'admin') {
        return res.status(403).json({ error: '没有权限' });
    }

    const nodeId = req.params.id;

    db.all(
        'SELECT s.*, u.username as owner_name FROM servers s LEFT JOIN users u ON s.user_id = u.id WHERE s.node_id = ? ORDER BY s.created_at DESC',
        [nodeId],
        (err, servers) => {
            if (err) {
                return res.status(500).json({ error: '获取服务器列表失败' });
            }
            res.json({ success: true, servers });
        }
    );
});

module.exports = router;